//
//  VoiceReadListViewController.m
//  ShowYork
//
//  Created by hxh on 2021/4/19.
//  Copyright © 2021 hxh. All rights reserved.
//


typedef enum : NSUInteger {
    XHREFRESHREADY,
    XHREFRESHSTART,
    XHREFRESHIDE,
    XHREFRESHEND,
} XHRefreshType;

#import "VoiceReadListViewController.h"
#import "VoiceReadItemDetailViewController.h"
#import "VoiceReadDetailViewController.h"
#import "VoiceReadLayerCell.h"
#import "VoiceReadListItemCell.h"
#import "VoiceReadHeaderView.h"
#import "JHCollectionViewFlowLayout.h"
#import "VoiceReadFooterView.h"
#import "VoiceReadTotalItemModel.h"
#import "VoiceReadPlayerItemModel.h"
#import "DFPlayer.h"


#define HeadIconH 80.0f
#define HeadMargin 20.0f
#define HeadBottom 21.0f

@interface VoiceReadListViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UIScrollViewDelegate,JHCollectionViewDelegateFlowLayout,DFPlayerDelegate,VoiceReadFooterViewDelegate,VoiceReadListItemCellDelegate,DFPlayerDataSource>
@property (nonatomic,strong)UICollectionView *collectionView;
@property (nonatomic,strong)VoiceReadHeaderView *headView;
@property (nonatomic,strong)VoiceReadFooterView *footerView;

// 导航栏相关组件
@property (nonatomic,strong)UIView *navView;
@property (nonatomic,strong)UIView *navContainView;
@property (nonatomic,strong)UIButton *backBtn;
@property (nonatomic,strong)UIImageView *backImgView;
@property (nonatomic,strong)UILabel *navLb;

// 刷新相关组件
@property (nonatomic,strong)UIActivityIndicatorView *spin;
@property (nonatomic,strong)UILabel *loadingLb;
@property (nonatomic,strong)UILabel *loadingDate;

@property (nonatomic,assign)XHRefreshType type;
@property (nonatomic,strong)VoiceReadTotalItemModel *itemModel;


@property (nonatomic,strong)NSMutableArray *voiceList;

@property (nonatomic,strong)VoiceReadPlayerItemModel *currentPlayModel;


@property (nonatomic,assign)long long beginTime;
@property (nonatomic,assign)CGFloat offsetHeight;

@property (nonatomic,assign)DFPlayerState remoteState;
@property (nonatomic,assign)DFPlayerState lastState;
@property (nonatomic,assign)DFPlayerState activityState;
@property (nonatomic,assign)DFPlayerState inHeadState;


@property (nonatomic,assign)BOOL isDraging;
@property (nonatomic,assign)BOOL isRemote;
@property (nonatomic,assign)BOOL isModal;
@property (nonatomic,assign)BOOL isActivity;

@property (nonatomic,assign)NSInteger errorCount;

@property (nonatomic,copy)NSArray *urls;


@property (nonatomic,strong)NSURLSessionTask *task;

@end

@implementation VoiceReadListViewController

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    if (self.isRemote) {
        if (self.remoteState == DFPlayerStatePlaying) {
            [[DFPlayer sharedPlayer] df_play];
        }
        if (self.remoteState == DFPlayerStatePause) {
            [[DFPlayer sharedPlayer] df_pause];
        }
    }
    self.isRemote = NO;
    
    [MobClick event:@"voice_list_show"];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if ([[DFPlayer sharedPlayer] currentAudioModel] != nil) {
        if (!self.isModal) {
            self.remoteState = [[DFPlayer sharedPlayer]state];
            [[DFPlayer sharedPlayer] df_pause];
            self.isRemote = YES;
        }
    }
    self.isModal = NO;
}

- (NSMutableArray *)voiceList{
    if (!_voiceList) {
        _voiceList = [NSMutableArray array];
    }
    return _voiceList;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUI];
    
    [self showDataLoadState];
    
    [self loadDataSource];
    
    [self setPlayer];
    

    
//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//
//    hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
//    //设置等待框背景色为黑色
//    hud.bezelView.backgroundColor = [UIColor blackColor];
//    
//    hud.removeFromSuperViewOnHide = YES;
//    //设置菊花框为白色
//    [UIActivityIndicatorView appearanceWhenContainedIn:[MBProgressHUD class], nil].color = [UIColor whiteColor];
//  
//    // Set the determinate mode to show task progress.
//    hud.mode = MBProgressHUDModeIndeterminate;
////
////    dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
////        // Do something useful in the background and update the HUD periodically.
////
////        dispatch_async(dispatch_get_main_queue(), ^{
////            [hud hideAnimated:YES];
////            sender.enabled = YES;
////        });
////    });
    
}
- (void)setUI{
    
    self.isHideNavBar = YES;
    
    self.headView = [[VoiceReadHeaderView alloc]init];
    [self.view addSubview:self.headView];
    
    JHCollectionViewFlowLayout *layout = [[JHCollectionViewFlowLayout alloc]init];
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH) collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.collectionView];
    
    [self.collectionView registerClass:[VoiceReadLayerCell class] forCellWithReuseIdentifier:@"VoiceReadLayerCell"];
    [self.collectionView registerClass:[VoiceReadListItemCell class] forCellWithReuseIdentifier:@"VoiceReadListItemCell"];
    

    CGSize size = [RPAppManager getTextSizeWithText:@"简介：读美文，读世界，读人生。含英咀华，破茧成蝶！" font:font(12) maxSize:CGSizeMake(kScreenW - 32, MAXFLOAT)];
    
    self.offsetHeight = kNavBarHeight  + HeadMargin * 2 + HeadBottom + HeadIconH + ceil(size.height);
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{

    }];

    [footer setTitle:@"—— 没有更多了 ——" forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = font(10);
    footer.stateLabel.textColor = RGBA(153, 153, 153, 1);
    footer.backgroundColor = [UIColor whiteColor];
    footer.hidden = YES;
    [footer endRefreshingWithNoMoreData];
    
    self.collectionView.mj_footer = footer;
    self.collectionView.contentInset = UIEdgeInsetsMake(self.offsetHeight, 0, 0, 0);
    
    
    self.navView = [[UIView alloc]init];
    self.navView.backgroundColor = RGBA(201, 197, 195, 1);
    [self.view addSubview:self.navView];
    [self.navView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(kNavBarHeight);
    }];
    
    self.navContainView = [[UIView alloc]init];
    [self.navView addSubview:self.navContainView];
    [self.navContainView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.equalTo(self.navView);
        make.height.mas_equalTo(44);
    }];

    self.backImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"common_back_normal_tag"]];
//    self.backImgView.highlightedImage = [UIImage imageNamed:@"common_back_tag"];
    [self.view addSubview:self.backImgView];
    [self.backImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.navContainView);
        make.left.equalTo(self.view).offset(16);
    }];
    
    self.backBtn = [[UIButton alloc]init];
    [self.backBtn addTarget:self action:@selector(backMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.backBtn];
    
    [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.equalTo(self.navContainView);
        make.width.mas_equalTo(80);
    }];
    
    self.navLb = [[UILabel alloc]init];
    self.navLb.text = @"-";
    self.navLb.font = [UIFont boldSystemFontOfSize:16];
    self.navLb.textColor = [UIColor whiteColor];
    [self.navContainView addSubview:self.navLb];
    
    [self.navLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.backImgView.mas_right).offset(8);
        make.centerY.equalTo(self.navContainView);
    }];
    
    self.navLb.alpha = 0;
    
    self.spin = [[UIActivityIndicatorView alloc] init];
    self.spin.color = [UIColor whiteColor];
    self.spin.hidden = YES;
    [self.view addSubview:self.spin];
    [self.spin mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(40, 40));
        make.top.equalTo(self.view).offset(GK_STATUSBAR_HEIGHT);
        make.centerX.equalTo(self.view).offset(-40);
    }];
    
    self.loadingLb = [[UILabel alloc]init];
    self.loadingLb.text = @"下拉刷新";
    self.loadingLb.textColor = UIColor.whiteColor;
    self.loadingLb.font = font(12);
    self.loadingLb.hidden = YES;
    [self.view addSubview:self.loadingLb];
    [self.loadingLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.spin).offset(-5);
        make.left.equalTo(self.spin.mas_right).offset(2);
    }];

    self.loadingDate = [[UILabel alloc]init];
    self.loadingDate.textColor = UIColor.whiteColor;
    self.loadingDate.text = [self dateStr];
    self.loadingDate.font = font(8);
    self.loadingDate.hidden = YES;
    [self.view addSubview:self.loadingDate];
    [self.loadingDate mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.loadingLb.mas_bottom);
        make.left.equalTo(self.spin.mas_right).offset(2);
    }];
    
    self.footerView = [[VoiceReadFooterView alloc]init];
    self.footerView.delegate = self;
    self.footerView.hidden = YES;
    [self.view addSubview:self.footerView];
    
    if (@available(iOS 11.0,*)) {
        self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

- (void)backMethod{
  
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)dealloc{
    [[DFPlayer sharedPlayer] df_clearUserCache:NO];
    [[DFPlayer sharedPlayer] df_deallocPlayer];
}

#pragma mark - network

- (void)loadDataSource{
    
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self loadVoiceItemSource];
    });
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self loadVoiceList];
    });
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        
        [self hideDataLoadLoadState];
        
        [self resetRefresh];
        
        self.navLb.text = self.itemModel.title;
        
        self.collectionView.mj_footer.hidden = self.itemModel.tvoiceAndResourceVMS.count == 0;
        
      
        __block NSInteger index = -1;
        // 判断播放器正在使用
        if ([DFPlayer sharedPlayer].state == DFPlayerStatePause ||
            [DFPlayer sharedPlayer].state  == DFPlayerStatePlaying) {
            [self.itemModel.tvoiceAndResourceVMS enumerateObjectsUsingBlock:^(VoiceReadListItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (self.currentPlayModel != nil && [obj.id isEqualToNumber:self.currentPlayModel.id]) {
                    index = idx;
                    if (self.currentPlayModel.status == XHPlayerListItemPlay) {
                        obj.status = XHItemStatusPlay;
                    }else if (self.currentPlayModel.status == XHPlayerListItemPause) {
                        obj.status = XHItemStatusPause;
                    }
                }
            }];
            
            [self dealVoiceListData];
        }
        
        // 没查询到，列表数据不为空
        if (index == -1 && self.currentPlayModel != nil) {
            [[DFPlayer sharedPlayer] df_clearUserCache:NO];
            // 关闭当前音源文件
            [[DFPlayer sharedPlayer] df_deallocPlayer];
            // 置空对象
            self.currentPlayModel = nil;
            // 隐藏
            self.footerView.hidden = YES;
        }
        
        // 根据内容偏移
        CGSize size = [RPAppManager getTextSizeWithText:[NSString stringWithFormat:@"简介：%@",self.itemModel.introduce] font:font(12) maxSize:CGSizeMake(kScreenW - 32, MAXFLOAT)];
        self.offsetHeight = kNavBarHeight + HeadMargin * 2 + HeadBottom + HeadIconH + ceil(size.height);
        self.collectionView.contentInset = UIEdgeInsetsMake(self.offsetHeight, 0, 0, 0);
        self.headView.cl_height = self.offsetHeight + 16.0f;
        [self.headView setItemModel:self.itemModel];
        [self.collectionView.mj_footer endRefreshingWithNoMoreData];
        self.collectionView.mj_footer.cl_height = 138.0f;
        self.collectionView.mj_insetB = 138.0f;
        [self.collectionView reloadData];
    });

}


- (void)loadVoiceItemSource{
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = @1;
    param[@"md5"] = [RPAppManager md5StrWithApi:VoiceGroup];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(VoiceGroup) parames:param success:^(id responseObj) {
        self.itemModel = [VoiceReadTotalItemModel mj_objectWithKeyValues:responseObj[RESPONSE]];
        dispatch_semaphore_signal(sema);
    } failure:^(NSError *error) {
        dispatch_semaphore_signal(sema);
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
  
    }];
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}

- (void)loadVoiceList{
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = @1;
    param[@"md5"] = [RPAppManager md5StrWithApi:VoicePlayList];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(VoicePlayList) parames:param success:^(id responseObj) {
        self.voiceList = [VoiceReadPlayerItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE]];
        dispatch_semaphore_signal(sema);
    } failure:^(id error) {
        dispatch_semaphore_signal(sema);
    }];
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}



#pragma mark - setPlayer
- (void)setPlayer{
//    [[DFPlayer sharedPlayer] df_initPlayerWithUserId:nil];
//    [DFPlayer sharedPlayer].playMode = DFPlayerModeOnlyOnce;
//    [DFPlayer sharedPlayer].isObserveWWAN = YES;
//    [DFPlayer sharedPlayer].isNeedCache = NO;
}


- (void)df_player:(DFPlayer *)player isInterrupted:(BOOL)isInterrupted{
    if (isInterrupted) {
        self.activityState = player.state;
        if ([DFPlayer sharedPlayer].state == DFPlayerStatePlaying) {
            [[DFPlayer sharedPlayer] df_pause];
            int totalTime = (int)([DFPlayer sharedPlayer].totalTime * 1000);
            int currentTime = (int)([DFPlayer sharedPlayer].currentTime * 1000);
            NSTimeInterval time = [[NSDate date] timeIntervalSince1970] * 1000;
            long long dTime = [[NSNumber numberWithDouble:time] longLongValue];
            long long bTime = self.beginTime;
            long long count = dTime - bTime;
            [self saveVideoTime:totalTime playTime:count beginTime:bTime endTime:dTime currentEndTime:currentTime];
        }
    }else{
        if ([DFPlayer sharedPlayer].state == DFPlayerStatePause) {
            [[DFPlayer sharedPlayer] df_play];
        }
    }
}

- (void)df_player:(DFPlayer *)player isHeadphone:(BOOL)isHeadphone{
    
    if (!isHeadphone) {
        
        if (self.currentPlayModel.status == XHPlayerListItemPlay) {
            
            self.currentPlayModel.status = XHPlayerListItemPause;
            
            [[DFPlayer sharedPlayer] df_pause];
            
            int totalTime = (int)([DFPlayer sharedPlayer].totalTime * 1000);
            int currentTime = (int)([DFPlayer sharedPlayer].currentTime * 1000);
            NSTimeInterval time = [[NSDate date] timeIntervalSince1970] * 1000;
            long long dTime = [[NSNumber numberWithDouble:time] longLongValue];
            long long bTime = self.beginTime;
            long long count = dTime - bTime;
            [self saveVideoTime:totalTime playTime:count beginTime:bTime endTime:dTime currentEndTime:currentTime];

            [self.footerView setItemModel:self.currentPlayModel];
            [self.footerView stopAnimation];
        
            self.inHeadState = DFPlayerStatePlaying;
            
            __block NSInteger index = -1;
            [self.itemModel.tvoiceAndResourceVMS enumerateObjectsUsingBlock:^(VoiceReadListItemModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                obj.status = XHItemStatusNormal;
                if ([self.currentPlayModel.id isEqualToNumber:obj.id]) {
                    obj.status = XHItemStatusPause;
                    index = idx;
                    *stop = YES;
                }
            }];
            if (index != -1) {
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:1];
                [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
            }
        }else if (self.currentPlayModel.status == XHPlayerListItemPause){
            self.inHeadState = DFPlayerStatePause;
        }

    }else{
        if (self.inHeadState == DFPlayerStatePlaying) {
            [[DFPlayer sharedPlayer] df_play];
            
            [self.footerView linearAnimation];
            
        }else if (self.inHeadState == DFPlayerStatePause){
            [[DFPlayer sharedPlayer] df_pause];
        }

    }
}

- (void)dealVoiceListData{
    NSNumber *sortType = [[NSUserDefaults standardUserDefaults] objectForKey:@"sortType"];
    [self.voiceList enumerateObjectsUsingBlock:^(VoiceReadPlayerItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.index = @(idx + 1);
    }];
    if (sortType.intValue == 1) {
       NSArray *sortArray = [self.voiceList sortedArrayUsingComparator:^NSComparisonResult(VoiceReadPlayerItemModel *_Nonnull obj1, VoiceReadPlayerItemModel *_Nonnull obj2) {
            return NSOrderedDescending;
        }];
        
        self.voiceList = [sortArray mutableCopy];
    }
    NSMutableArray *urls = [NSMutableArray array];
    [self.voiceList enumerateObjectsUsingBlock:^(VoiceReadPlayerItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        DFPlayerModel *model = [[DFPlayerModel alloc]init];
        model.audioUrl = [NSURL URLWithString:obj.url];
        model.audioId = idx;
        [urls addObject:model];
    }];
    self.urls = [urls mutableCopy];
    
    [[DFPlayer sharedPlayer] df_reloadData];
}



- (void)df_player:(DFPlayer *)player progress:(CGFloat)progress currentTime:(CGFloat)currentTime{

    
    self.errorCount = 0;

    if (self.currentPlayModel != nil) {
        __block NSInteger index = -1;
        [self.itemModel.tvoiceAndResourceVMS enumerateObjectsUsingBlock:^(VoiceReadListItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.id isEqualToNumber:self.currentPlayModel.id]) {
                index = idx;
                *stop = YES;
            }
        }];
        
        if (index != -1) {
            VoiceReadListItemModel *itemModel = self.itemModel.tvoiceAndResourceVMS[index];
            // 状态切换
            if (player.state == DFPlayerStatePause && self.lastState != player.state) {
                itemModel.status = XHItemStatusPause;
                int totalTime = (int)(player.totalTime * 1000);
                int currentTime = (int)(player.currentTime * 1000);
                NSTimeInterval time = [[NSDate date] timeIntervalSince1970] * 1000;
                long long dTime = [[NSNumber numberWithDouble:time] longLongValue];
                long long bTime = self.beginTime;
                long long count = dTime - bTime;
                [self saveVideoTime:totalTime playTime:count beginTime:bTime endTime:dTime currentEndTime:currentTime];
             
                [self.collectionView reloadData];
            }
            if (player.state == DFPlayerStatePlaying) {
                itemModel.status = XHItemStatusPlay;
                if (player.totalTime != 0 && self.beginTime == 0) {
                    NSTimeInterval time = [[NSDate date] timeIntervalSince1970] * 1000;
                    self.beginTime = [[NSNumber numberWithDouble:time] longLongValue];
                }
                [self.collectionView reloadData];
            }
        }

    }
    
    if (player.state == DFPlayerStatePause) {
        self.currentPlayModel.status = XHPlayerListItemPause;
    }else if (player.state == DFPlayerStatePlaying){
        self.currentPlayModel.status = XHPlayerListItemPlay;
    }else{
        self.currentPlayModel.status = XHPlayerListItemNormal;
    }
    self.currentPlayModel.totalTime = player.totalTime;
    self.currentPlayModel.currentTime = currentTime;
    
    [self.footerView setItemModel:self.currentPlayModel];
    
    self.lastState = [DFPlayer sharedPlayer].state;
}

- (void)df_playerDidPlayToEndTime:(DFPlayer *)player{
    [player df_next];
}

//加入播放队列
- (void)df_playerAudioAddToPlayQueue:(DFPlayer *)player{
    
}
//缓冲进度代理
- (void)df_player:(DFPlayer *)player bufferProgress:(CGFloat)bufferProgress{
  
}

#pragma mark - 统一保存时间
- (void)saveVideoTime:(int)totalTime playTime:(long long)playTime beginTime:(long long)bTime endTime:(long long)endTime currentEndTime:(int)currentEndTime{
    if (bTime == 0) {
        return;
    }
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"mediaTime"] = @(totalTime);
    param[@"playTime"] = @(playTime);
    param[@"startTime"] = @(bTime);
    param[@"endTime"] = @(endTime);
    param[@"mediaId"] = self.currentPlayModel.id;
    param[@"resourceId"] = self.currentPlayModel.resourceId;
    param[@"currentEndTime"] = @(currentEndTime);
    param[@"md5"] = [RPAppManager md5StrWithApi:SaveVoiceLog];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(SaveVoiceLog) parames:param success:^(id responseObj) {

    } failure:^(id error) {

    }];
    self.beginTime = 0;
}

#pragma mark - tableViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    if (self.itemModel == nil) {
        return 0;
    }
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }
    return self.itemModel.tvoiceAndResourceVMS.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        VoiceReadLayerCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"VoiceReadLayerCell" forIndexPath:indexPath];
        return cell;
    }else{
        VoiceReadListItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"VoiceReadListItemCell" forIndexPath:indexPath];
        cell.model = self.itemModel.tvoiceAndResourceVMS[indexPath.item];
        cell.delegate = self;
        return cell;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return CGSizeMake(kScreenW, 16);
    }else{
        CGFloat width = (kScreenW - 17 - 14 - 2 * 16)/3;
        CGFloat height = width/3 * 4 + 40;
        return CGSizeMake(width, height);
    }
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    if (section == 0) {
        return UIEdgeInsetsZero;
    }else{
        return UIEdgeInsetsMake(0, 17, 0, 14);
    }
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    if (section == 0) {
        return 0.01f;
    }
    return 12.0f;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    if (section == 0) {
        return 0.01f;
    }
    return 8.0f;;
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
   
    CGFloat y = scrollView.contentOffset.y;
    
    if (-y > self.offsetHeight) {
        self.headView.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.frame),-y + 16);
        self.navLb.alpha = 0;
    }else{
        CGFloat alpha = y / self.offsetHeight;
        if (y <= 0) {
            self.navLb.alpha = 1 - fabs(alpha);
        }else{
            self.navLb.alpha = 1;
        }
        if (self.type == XHREFRESHIDE && fabs(alpha) < 1.0f) {
            self.loadingDate.hidden = YES;
            self.loadingLb.hidden = YES;
            self.spin.hidden = YES;
        }
        
        if (self.type != XHREFRESHIDE) {
            self.loadingDate.hidden = YES;
            self.loadingLb.hidden = YES;
            self.spin.hidden = YES;
        }
    }
    
    
    if (y < - self.offsetHeight && self.isDraging) {
        self.spin.hidden = NO;
        self.loadingDate.hidden = NO;
        self.loadingLb.hidden = NO;

        // 判断如果是非正在请求
        if (self.type != XHREFRESHIDE) {
            // 改成开始请求
            self.type = XHREFRESHREADY;
        }
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    self.isDraging = YES;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    if (decelerate) {
        CGFloat y = scrollView.contentOffset.y;
        if (y <= - 200) {
            if (self.type == XHREFRESHREADY) {
                self.type = XHREFRESHIDE;
                [self.spin startAnimating];
            }
            self.loadingLb.text = @"正在刷新";
        }else{
            [self resetRefresh];
        }
    }
    self.isDraging = NO;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if ([self.spin isAnimating]) {
        if ([self.collectionView.mj_footer isRefreshing]) {
            [self resetRefresh];
        }else{
            [self loadDataSource];
        }
    }else{
        [self resetRefresh];
    }
}

- (void)resetRefresh{
    [self.spin stopAnimating];
    self.loadingDate.hidden = YES;
    self.loadingLb.hidden = YES;
    self.loadingLb.text = @"下拉刷新";
    self.type = XHREFRESHREADY;
}

- (NSString *)dateStr{
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    return [formatter stringFromDate:date];
}

- (UIColor *)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout backgroundColorForSection:(NSInteger)section{
    if (section == 0) {
        return [UIColor clearColor];
    }
    return [UIColor whiteColor];
}

#pragma mark - footerViewDelegate
- (void)footerViewPlayWithCurrentModel:(VoiceReadPlayerItemModel *)currentModel{
    [[DFPlayer sharedPlayer] df_play];
}
- (void)footerViewPauseWithCurrentModel:(VoiceReadPlayerItemModel *)currentModel{
    [[DFPlayer sharedPlayer] df_pause];
}
- (void)footerViewDeleteWithCurrentModel:(VoiceReadPlayerItemModel *)currentModel{
    
    __block NSInteger index = -1;
    [self.itemModel.tvoiceAndResourceVMS enumerateObjectsUsingBlock:^(VoiceReadListItemModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.status = XHItemStatusNormal;
        if ([currentModel.id isEqualToNumber:obj.id]) {
            index = idx;
            *stop = YES;
        }
    }];
    if (index != -1) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:1];
        [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
    }
    self.beginTime = 0;
    self.currentPlayModel = nil;
    
    [[DFPlayer sharedPlayer] df_clearUserCache:NO];
    [[DFPlayer sharedPlayer] df_deallocPlayer];
}

#pragma mark - VoiceReadListItemCellDelegate
- (void)showVoiceDetailWithCurrentModel:(VoiceReadListItemModel *)currentModel{
    
//    VoiceReadDetailViewController *v = [[VoiceReadDetailViewController alloc]init];
//    v.voiceId = currentModel.id;
//    [self.navigationController pushViewController:v animated:YES];
//    return;
//
    
    if (currentModel == nil) {
        return;
    }
    self.isModal = YES;

    VoiceReadItemDetailViewController *vc = [[VoiceReadItemDetailViewController alloc]init];
    NavigationViewController *nav = [[NavigationViewController alloc]initWithRootViewController:vc];

    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    vc.voiceId = currentModel.id;
    vc.sourceArray = self.voiceList;
    vc.webUrl = [NSString stringWithFormat:@"%@media/audio?id=%@&isApp=true",HtmlUrl,currentModel.id];
    // 判断点击进入
    if (self.currentPlayModel != nil && currentModel.id != nil && [self.currentPlayModel.id isEqualToNumber:currentModel.id]) {
        vc.currentModel = self.currentPlayModel;
        vc.beginTime = self.beginTime;
    // 不同
    }else{
        // 判断播放器状态
        if ([DFPlayer sharedPlayer].state == DFPlayerStatePlaying) {

            self.currentPlayModel.status = XHPlayerListItemNormal;

            int totalTime = (int)([DFPlayer sharedPlayer].totalTime * 1000);
            int currentTime = (int)([DFPlayer sharedPlayer].currentTime * 1000);
            NSTimeInterval time = [[NSDate date] timeIntervalSince1970] * 1000;
            long long dTime = [[NSNumber numberWithDouble:time] longLongValue];
            long long bTime = self.beginTime;
            long long count = dTime - bTime;
            [self saveVideoTime:totalTime playTime:count beginTime:bTime endTime:dTime currentEndTime:currentTime];

            [[DFPlayer sharedPlayer] df_clearUserCache:NO];
            // 关闭当前音源文件
            [[DFPlayer sharedPlayer] df_deallocPlayer];
            // 置空对象
            self.currentPlayModel = nil;
            // 隐藏
            self.footerView.hidden = YES;
            // 当前时间置空
            self.beginTime = 0;
            // 刷表
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.itemModel.tvoiceAndResourceVMS enumerateObjectsUsingBlock:^(VoiceReadListItemModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    obj.status = XHItemStatusNormal;
                }];
                [self.collectionView reloadData];
            });
        }
    }

    [self presentViewController:nav animated:YES completion:nil];

    __weak typeof(self)weakSelf = self;

    vc.playVoice = ^(VoiceReadPlayerItemModel *currentModel, long long bTime, NSArray *urls, NSArray *sourceArray) {

        weakSelf.footerView.hidden = NO;
        weakSelf.urls = urls;
        weakSelf.beginTime = bTime;
        [weakSelf.voiceList removeAllObjects];
        [weakSelf.voiceList addObjectsFromArray:sourceArray];

        // 根据ID去查询列表中对应播放的数据
        [weakSelf.itemModel.tvoiceAndResourceVMS enumerateObjectsUsingBlock:^(VoiceReadListItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.id != nil && currentModel.id != nil && [obj.id isEqualToNumber:currentModel.id]) {
                // 判断状态
                if (currentModel.status == XHPlayerListItemPlay) {
                    obj.status = XHItemStatusPlay;
                }else if (currentModel.status == XHPlayerListItemPause){
                    obj.status = XHItemStatusPause;
                }
            }else{
                obj.status = XHItemStatusNormal;
            }
        }];

        // 设置底部状态
        [weakSelf.footerView setCoverUrl:currentModel.cover];
        [weakSelf.footerView setTitle:currentModel.title];
        [weakSelf.footerView setItemModel:currentModel];
        // 设置是否可以滚动
        if (currentModel.status == XHPlayerListItemPlay) {
            weakSelf.lastState = DFPlayerStatePlaying;
            [weakSelf.footerView linearAnimation];
        }else if (currentModel.status == XHPlayerListItemPause){
            weakSelf.lastState = DFPlayerStatePause;
            [weakSelf.footerView stopAnimation];
        }else{
            weakSelf.lastState = DFPlayerStateUnknown;
            [weakSelf.footerView stopAnimation];
        }
        weakSelf.currentPlayModel = currentModel;
        [weakSelf.collectionView reloadData];
        [DFPlayer sharedPlayer].delegate = weakSelf;
        [DFPlayer sharedPlayer].dataSource = weakSelf;
        [[DFPlayer sharedPlayer] df_reloadData];
    };

    vc.playOther = ^{
        weakSelf.currentPlayModel = nil;
        weakSelf.lastState = DFPlayerStateUnknown;
        [weakSelf.footerView stopAnimation];
        weakSelf.footerView.hidden = YES;

        [self.itemModel.tvoiceAndResourceVMS enumerateObjectsUsingBlock:^(VoiceReadListItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.status = XHItemStatusNormal;
        }];
        [self.collectionView reloadData];
    };
}

#pragma mark - DFPlayDataSource

- (NSArray<DFPlayerModel *> *)df_audioDataForPlayer:(DFPlayer *)player{
    return self.urls;
}

- (DFPlayerInfoModel *)df_audioInfoForPlayer:(DFPlayer *)player{
    NSInteger index = player.currentAudioModel.audioId;
    VoiceReadPlayerItemModel *voiceItemModel = self.voiceList[index];
    voiceItemModel.status = XHPlayerListItemReady;
    if (self.currentPlayModel != nil && self.currentPlayModel.status == XHPlayerListItemPlay) {
        self.currentPlayModel.status = XHPlayerListItemNormal;
        int totalTime = (int)(self.currentPlayModel.totalTime * 1000);
        int currentTime = (int)(self.currentPlayModel.currentTime * 1000);
        NSTimeInterval time = [[NSDate date] timeIntervalSince1970] * 1000;
        long long dTime = [[NSNumber numberWithDouble:time] longLongValue];
        long long bTime = self.beginTime;
        long long count = dTime - bTime;
        [self saveVideoTime:totalTime playTime:count beginTime:bTime endTime:dTime currentEndTime:currentTime];
    }
    // 处理状态
    [self.itemModel.tvoiceAndResourceVMS enumerateObjectsUsingBlock:^(VoiceReadListItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.status = XHItemStatusNormal;
    }];

    self.currentPlayModel = voiceItemModel;
    self.beginTime = 0;
    DFPlayerInfoModel *infoModel = [[DFPlayerInfoModel alloc]init];
    infoModel.audioName = voiceItemModel.title;
    infoModel.audioSinger = voiceItemModel.author;

    NSString *strUrl = voiceItemModel.cover;
    
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    NSString* key = [manager cacheKeyForURL:[NSURL URLWithString:strUrl]];
    SDImageCache* cache = [SDImageCache sharedImageCache];
    //此方法会先从memory中取。
    UIImage *image = [cache imageFromDiskCacheForKey:key];
    infoModel.audioImage = image;

    // 设置底部
    [self.footerView setCoverUrl:voiceItemModel.cover];
    [self.footerView setTitle:voiceItemModel.title];
    [self.footerView setItemModel:voiceItemModel];
    [self.footerView linearAnimation];
    
    [self.collectionView reloadData];
    
    // 请求详情接口
    [self loadVoiceDetail];
    

    return infoModel;
}



- (void)df_playerUpdateSeekTimeToPlay:(DFPlayer *)player{
    
    if (player.state == DFPlayerStatePlaying) {
        int totalTime = (int)(player.totalTime * 1000);
        int currentTime = (int)([player currentTime] * 1000);
        NSTimeInterval time = [[NSDate date] timeIntervalSince1970] * 1000;
        long long dTime = [[NSNumber numberWithDouble:time] longLongValue];
        long long bTime = self.beginTime;
        long long count = dTime - bTime;
        [self saveVideoTime:totalTime playTime:count beginTime:bTime endTime:dTime currentEndTime:currentTime];
    }
}
- (void)df_playerEndedSeekTimeToPlay:(DFPlayer *)player{
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970] * 1000;
    self.beginTime = [[NSNumber numberWithDouble:time] longLongValue];
}

// 进入后台
- (void)df_playerEnterBackGroundToPlay:(DFPlayer *)player{
    self.isActivity = NO;
}
// 进入前台
- (void)df_playerActivityToPlay:(DFPlayer *)player{
    self.isActivity = YES;
    
    if (self.activityState == DFPlayerStatePlaying) {
        [[DFPlayer sharedPlayer] df_play];
    }
    if (self.activityState == DFPlayerStatePause) {
        [[DFPlayer sharedPlayer] df_pause];
    }
}

//状态信息代理
- (void)df_player:(DFPlayer *)player didGetStatusCode:(DFPlayerStatusCode)statusCode{
    if (statusCode == DFPlayerStatusFailed || statusCode == DFPlayerStatusNoNetwork){
        self.errorCount++;
        self.currentPlayModel.status = XHPlayerListItemFailed;
        if (self.errorCount <= 1) {
            [WHToast showMessage:@"抱歉，播放出错了" duration:2 finishHandler:nil];
        }
        // 全部失效
        if ([self isErrorList]) {
            self.currentPlayModel = nil;
            self.beginTime = 0;
            [self.footerView stopAnimation];
            self.footerView.hidden = YES;
            [self.itemModel.tvoiceAndResourceVMS enumerateObjectsUsingBlock:^(VoiceReadListItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                obj.status = XHItemStatusNormal;
            }];
            [self.collectionView reloadData];
            return;
        }
        // 判断是上一首播放出错还是下一首播放出错
        if ([DFPlayer sharedPlayer].isLast) {
            [[DFPlayer sharedPlayer] df_last];
        }else{
            [[DFPlayer sharedPlayer] df_next];
        }
    }
}
- (void)df_playerFailToPlay:(DFPlayer *)player StatusCode:(NSInteger)statusCode{
   
    self.errorCount++;
    if (self.errorCount <= 1) {
        [WHToast showMessage:@"抱歉，播放出错了" duration:2 finishHandler:nil];
    }
    self.currentPlayModel.status = XHPlayerListItemFailed;
    // 全部失效
    if ([self isErrorList]) {
        self.currentPlayModel = nil;
        self.beginTime = 0;
        [self.footerView stopAnimation];
        self.footerView.hidden = YES;
        [self.itemModel.tvoiceAndResourceVMS enumerateObjectsUsingBlock:^(VoiceReadListItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.status = XHItemStatusNormal;
        }];
        [self.collectionView reloadData];
        return;
    }
    // 判断是上一首播放出错还是下一首播放出错
    if ([DFPlayer sharedPlayer].isLast) {
        [[DFPlayer sharedPlayer] df_last];
    }else{
        [[DFPlayer sharedPlayer] df_next];
    }
}

- (BOOL)isErrorList{
    __block BOOL isError = YES;
    [self.voiceList enumerateObjectsUsingBlock:^(VoiceReadPlayerItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.status != XHPlayerListItemFailed) {
            isError = NO;
            *stop = YES;
        }
    }];
    return isError;
}

- (void)loadVoiceDetail{
    
    [self.task cancel];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = self.currentPlayModel.id;
    param[@"md5"] = [RPAppManager md5StrWithApi:VoiceDetails];
    self.task = [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(VoiceDetails) parames:param success:^(id responseObj) {
    
    } failure:^(NSError *error) {
    
    }];
}


@end
